package com.lee.demo1.business;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.lee.demo1.dao.ArticleMapper;
import com.lee.demo1.dao.CategoryMapper;
import com.lee.demo1.dao.PictureMapper;
import com.lee.demo1.domain.Article;
import com.lee.demo1.domain.Category;
import com.lee.demo1.domain.Picture;


/**
 * 文章管理类
 * @author leopad
 *
 */
@Service
public class ArticleBusiness {
	
	private static Logger logger = LoggerFactory.getLogger(ArticleBusiness.class);
	
	@Resource
	private ArticleMapper articleMapper;
	@Resource
	private CategoryMapper categoryMapper;
	@Resource
	private PictureMapper pictureMapper;
	
	@Value("${upload.images.dir}")
	private String uploadImagesDir;
	
	
	public String getUploadImagesDir() {
		return uploadImagesDir;
	}
	public void setUploadImagesDir(String uploadImagesDir) {
		this.uploadImagesDir = uploadImagesDir;
	}
	
	
	public Article getArticleById(int id){
		return articleMapper.selectByPrimaryKey(id);
	}
	/**
	 * 取得类别
	 * @return
	 */
	public List<Category> getCategories(){
		return categoryMapper.selectAllCategoryBySort();
	}
	/**
	 * 新增加文章
	 * @param article
	 * @return
	 */
	public int addArticle(Article article){
		article.setPubDatetime(new Date());
		//article.setAuthor("admin");
		return articleMapper.insert(article);
	}
	
	public int getAeticleCount(Map<String,Object> map){
		return articleMapper.selectByConditionsCount(map);
	}
	
	public List<Article> getInstructonsList(Map<String,Object> map){
		return articleMapper.selectByConditionsForPading(map);
	}
	
	public Article getArticle(int id){
		return articleMapper.selectByPrimaryKey(id);
	}
	
	public int updateArticle(Article article){
		return articleMapper.updateByPrimaryKeySelective(article);
	}
	
	public int deleteArticle(int id){
		return articleMapper.deleteByPrimaryKey(id);
	}
	
	public void uploadPicture(HttpServletRequest request, int articleId){
		
		List<Picture> imgList = new ArrayList<Picture>();
		MultipartHttpServletRequest mul = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = mul.getFiles("_img");
		for (int i = 0; i < files.size(); i++) {
			CommonsMultipartFile cmf = (CommonsMultipartFile) files.get(i);
			if(cmf.getSize()>0){
				String dir1 = cn.com.mylib.www.DateUtils.getSysDate("yyyyMMdd");
				String fileName =  String.valueOf(System.currentTimeMillis());
				
				StringBuilder newFileName = new StringBuilder();
				newFileName.append( request.getRealPath("/") )
						   .append( uploadImagesDir )
						   .append( File.separator )
						   .append( dir1 );
				
				try {//创建目录
					FileUtils.forceMkdir(new File( newFileName.toString() ));
				} catch (IOException e1) {
					logger.error("-------------" + e1);
				}
				newFileName.append( File.separator )
				   		   .append( fileName )
				   		   .append( FilenameUtils.EXTENSION_SEPARATOR_STR )
				   		   .append( FilenameUtils.getExtension( cmf.getOriginalFilename() ) );
				File file = new File( newFileName.toString());
				OutputStream os = null;
				try {
					os = new FileOutputStream( file );
					IOUtils.write( cmf.getBytes(), os );
				} catch (FileNotFoundException e) {
					logger.error("--------- FileNotFoundException" + e);
				} catch (IOException e) {
					logger.error("--------- IOException" + e);
				} finally {
					try {
						os.close();
					} catch (IOException e) {
						logger.error("--------- IOException" + e);
					}
				}
				//3、生成图片web路径，用于保存数据库中，用于页面显示
				StringBuilder webShowUrl = new StringBuilder();
				webShowUrl.append(uploadImagesDir)
						.append("/")
						.append(dir1)
						.append("/")
						.append( fileName )
				   		.append( FilenameUtils.EXTENSION_SEPARATOR_STR )
				   		.append( FilenameUtils.getExtension( cmf.getOriginalFilename() ) );
				
				Picture pic = new Picture();
				pic.setArticleId(articleId);
				pic.setPath(webShowUrl.toString());
				imgList.add(pic);
			}
		}
		if(imgList.size()>0){
			pictureMapper.insertPictureBatch(imgList);
		}
	}
	
	public List<Picture> getPictures(int articleId){
		
		return pictureMapper.selectByArticleId(articleId);
	}
	
	
	public int updatePicture(int id, String description, Integer sort){
		
		Picture pic = new Picture();
		pic.setId(id);
		if(StringUtils.isNotBlank(description)){
			pic.setDescription(description);
		}
		if(null != sort){
			pic.setSort(sort);
		}
		return pictureMapper.updateByPrimaryKeySelective(pic);
		
	}
}
